package com.lmf.juc.AsynchronousCallback;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.BiConsumer;
import java.util.function.Supplier;

/**
 * 演示异步回调方法：两种
 */
public class AsynchronousCallbackDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * 方法一：没有返回值的异步回调方法
         */
        CompletableFuture<Void> async = CompletableFuture.runAsync(()->{
            //添加一个线程进去
            System.out.println(Thread.currentThread().getName() + ": CompletableFuture1,runAsync");
        });
        //获取那个线程的执行结果,并打印
        System.out.println(async.get());
        System.out.println("----------------------------------------");


        /**
         * 方法二：有返回值的异步回调方法
         */
        CompletableFuture<Integer> async1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                System.out.println(Thread.currentThread().getName() + ": CompletableFuture2,supplyAsync");
                //模拟异常
                int i = 10/0;
                return 1024;
            }
        });
        //获取AA线程的执行结果,并打印
//        System.out.println(async1.get());
        //另外一种获取返回值的方法
        async1.whenComplete(new BiConsumer<Integer, Throwable>() {
            /**
             * @param integer：AA线程的返回结果
             * @param throwable：AA线程存在的异常信息
             */
            @Override
            public void accept(Integer integer, Throwable throwable) {
                System.out.println(Thread.currentThread().getName() + "线程回调结果:" + integer);
                System.out.println(Thread.currentThread().getName() + "线程存在的异常信息:" + throwable);
            }
        }).get();
        System.out.println("----------------------------------------");


        //有返回值的异步回调方法
        CompletableFuture<Integer> async2 = CompletableFuture.supplyAsync(()->{
            System.out.println(Thread.currentThread().getName() + ": CompletableFuture2,supplyAsync");
            //模拟异常
            int i = 10/0;
            return 1024;
        });
        async2.whenComplete((t,u)->{
            System.out.println("------t="+t);//返回值
            System.out.println("------u="+u);//异常信息
        }).get();
    }
}
